import {computed, getCurrentInstance, inject, nextTick, onBeforeUnmount, onMounted, type Ref} from "vue";
import type InputProps from "../type/InputProps.ts";
import type InputEmits from "../type/InputEmits.ts";
import type InputComponent from "../type/InputComponent.ts";

import {useInputCore} from './useInputCore'
import {useInputValidation} from './useInputValidation'
import {useInputEvents} from './useInputEvents'
import {useNumberInput} from './useNumberInput'
import {useInputHelpers} from './useInputHelpers'
import {usePasswordInput} from './usePasswordInput'


/**
 * created by yangtong on 2025/6/16 下午9:46
 * <br/>
 * 主入口文件
 */
export function useInput(props: InputProps, emit: InputEmits) {

    // 核心状态
    const coreState = useInputCore(props, emit)

    // 校验逻辑
    const validation = useInputValidation(props)

    // 辅助功能
    const helpers = useInputHelpers(props)

    // 密码输入框
    const passwordInput = usePasswordInput()

    // 数字输入框
    const numberInput = useNumberInput(props, emit, coreState.displayValue)

    // 事件处理
    const events = useInputEvents(
        props,
        emit,
        {
            errorMessage: validation.errorMessage,
            ...coreState,
            normalizedModelValue: coreState.normalizedModelValue
        },
        {
            allowsCheck: helpers.allowsCheck,
            validate: validation.validate,
            formatValue: helpers.formatValue
        }
    )
    const instance = getCurrentInstance()
    const attrs = instance?.attrs ?? {}
    // 通用属性
    const commonAttrs = computed(() => ({
        ...attrs,
        placeholder: props.placeholder,
        disabled: props.disabled,
        autocomplete: props.autocomplete,
        ...events
    }))

    // 清空输入
    const cleanInput = () => {
        helpers.cleanInput(emit, coreState.displayValue)
        nextTick(() => {
            validation.validate()
        })
    }

    // 暴露给外部的对象
    const inputComponent: InputComponent = {
        validate: () => validation.validate(),
        clearError: () => validation.clearError(),
        getValue: () => props.modelValue,
        setValue: (value: string | number | null | undefined) => emit('update:modelValue', value),
        getErrorMessage: () => validation.errorMessage.value,
        getFieldName: () => props.label || props.placeholder,
        isRequired: () => props.required || (props.useRules?.includes('required') ?? false),
        instance
    }

    const formRegister = inject<((component: InputComponent) => void) | undefined>('register', undefined)
    const formUnregister = inject<((component: InputComponent) => void) | undefined>('unregister', undefined)

    // 注册到表单系统
    if (formRegister && formUnregister) {
        onMounted(() => {
            // 延迟注册，确保组件完全初始化
            nextTick(() => {
                formRegister(inputComponent)
                //console.debug(`[Form] Input field "${inputComponent.getFieldName()}" registered to form`)
            })
        })

        onBeforeUnmount(() => {
            formUnregister(inputComponent)
            //console.debug(`[Form] Input field "${inputComponent.getFieldName()}" unregistered from form`)
        })
    }

    return {
        // 核心状态
        ...coreState,

        // 校验
        ...validation,

        // 样式相关
        lightBorderColor: helpers.lightBorderColor,

        // 密码输入框
        ...passwordInput,

        // 数字输入框
        ...numberInput,

        // 其他
        commonAttrs,
        formFieldExposed: inputComponent,
        cleanInput
    }
}